﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;

namespace PlanningGIS.ArcGIS
{
    /// <summary>
    /// 地图文档操作类
    /// </summary>
    public class DocumentHelper
    {
        /// <summary>
        /// 修改地图文档的数据源路径
        /// </summary>
        /// <param name="mxd">地图文档路径</param>
        /// <param name="oldpath">之前的路径</param>
        /// <param name="newpath">要修改的路径</param>
        /// <param name="useRelative">是否使用相对路径</param>
        public static void SetDataSource(string mxd, string oldpath, string newpath, bool useRelative = true)
        {
            IMapDocument mapDocument = new MapDocument();
            mapDocument.Open(mxd); //打开本地的abc地图文档，用来操作改mxd文件
            IMap map = mapDocument.get_Map(0);
            IMapLayers mapLayer = map as IMapLayers;
            int count = mapLayer.LayerCount;
            for (int i = 0; i < count; i++)
            {
                ILayer layer = mapLayer.get_Layer(i);
                if (layer is IDataLayer2)
                {
                    IDataLayer2 datalyr = layer as IDataLayer2;
                    IDatasetName dsname = datalyr.DataSourceName as IDatasetName;
                    IWorkspaceName2 wksname = dsname.WorkspaceName as IWorkspaceName2;
                    string PathName = wksname.PathName;
                    wksname.PathName = PathName.Replace(oldpath, newpath);
                }
            }
            mapDocument.Save(useRelative);
        }
    }
}
